package com.le.tester.leetcode;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * createTime：2022/5/28 15:12
 * description：多数元素
 */
public class MajorityElement {
    public int majorityElement(int[] nums) {

        int n = nums.length;
        int times = n / 2;

//        Map<Integer, Integer> numsMap = new HashMap<>();
//        //List<Integer> collect = Stream.of(nums).collect(Collectors.toList());
//
//        for (Integer item : nums) {
//            Integer index = numsMap.get(item);
//            numsMap.put(item, Objects.isNull(index) ? 1 : index + 1);
//        }
        //.boxed装进箱子里面，分组统计
        Map<Integer, Long> numsMap = Arrays.stream(nums).boxed().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        for (Map.Entry entryItem : numsMap.entrySet()) {
            Integer key = (Integer) entryItem.getKey();
            Long value = (Long) entryItem.getValue();
            if (value > times) {
                return key;
            }
        }
        return 0;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{2, 2, 1, 1, 1, 2, 2};
        System.out.println(new MajorityElement().majorityElement(nums));
    }
}
